<?php
class IndexAction extends Action {
	
	//显示验证码  
	public function verifyDisplay() {
		$this->display ();
	}
	
	// 生成验证码  
	public function verify() {
		import ( "ORG.Util.Image" );
		Image::buildImageVerify ();
	}
	
	public function index() {
		//防止页面乱码  
		header('Content-type:text/html;charset=utf-8');
		if(!session('admin')) {
			echo "<script language=\"javascript\">alert('请先登录!');window.location='login'</script>";
		} else {
			$this->display();
		}
	}
	
	//验证登录
	public function login() {
		function getIP() {
			//$ip; 
			if (getenv ( "HTTP_X_FORWARDED_FOR" ))
				$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
			else if (getenv ( "HTTP_CLIENT_IP" ))
				$ip = getenv ( "HTTP_CLIENT_IP" );
			else if (getenv ( "REMOTE_ADDR" ))
				$ip = getenv ( "REMOTE_ADDR" );
			else
				$ip = "Unknow ";
			return $ip;
		}
		
		//防止页面乱码  
		header('Content-type:text/html;charset=utf-8');
		if($_POST['sub']) {
			if (md5 ($_POST['verifyDisplay']) != $_SESSION['verify']) {
				echo "<script language=\"javascript\">alert('验证码错误');window.location='login'</script>";
			} else {
				$Dao = M ("Admin"); // 实例化模型类
				// 构建写入的数据数组
				$data ["admin_name"] = $_POST["username"];
				$data ["admin_pwd"] = md5 ($_POST["password"]);
				// 查询数据
				$admin = $Dao->getByAdminName ($data["admin_name"]);
				if (!$admin||$admin["admin_state"]!=1) {
					echo "<script language=\"javascript\">alert('用户名不存在');window.location='login'</script>";
				} else if ($admin ["admin_pwd"] != $data ["admin_pwd"]) {
					echo "<script language=\"javascript\">alert('密码错误');window.location='login'</script>";
				} else {
					$update["admin_last_date"] = $admin["admin_now_date"];
					$update["admin_last_ip"] = $admin["admin_now_ip"];
					$update["admin_now_date"] = "20".date ( 'y-m-d H:i:s', time () );
					$update["admin_now_ip"] = getIP();
					$condition["admin_id"] = $admin["admin_id"];
					$Dao->where($condition)->save($update);
				
					$admininfo = $Dao->getByAdminName ( $_POST ["username"] );
					setcookie(session_name(),session_id(),time() + 3000,"/"); //设置session生存期
					session('admin',$admininfo);
					$this->redirect('index');
				}
			}
		} else {
			$this->display();	
		}
	}
	
	public function logout() {
		header ( 'Content-type:text/html;charset=utf-8' );
		$Dao = M ( "Admin" ); // 实例化模型类
		
		$admin = $Dao->getByAdminName ( $_COOKIE['adminName'] );
		$update["admin_last_date"] = $admin["admin_now_date"];
		$update["admin_last_ip"] = $admin["admin_now_ip"];
		$condition["admin_id"] = $admin["admin_id"];
		$Dao->where($condition)->save($update);
		session('[destroy]');
		
		//跳转回登录页面
		echo "<script language=\"javascript\">top.location.href='login';</script>";
	}
}